import openpyxl

# import pandas as pd
# from selenium import webdriver
# from selenium.webdriver.edge.service import Service
# from selenium.webdriver.common.by import By
# from selenium.webdriver.support.ui import WebDriverWait
# from selenium.webdriver.support import expected_conditions as EC
import time
from openpyxl import load_workbook
import requests
import json
import random
import warnings
from requests.adapters import HTTPAdapter
import urllib3
from urllib3.util.retry import Retry

# 完全禁用SSL警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# def get_csdn_article_views(url):
#     # 设置Edge WebDriver路径
#     service = Service("C:/Users/lwx1364338/Desktop/外媒阅读数刷新/drive/msedgedriver.exe")  # 替换为你的msedgedriver路径
#     driver = webdriver.Edge(service=service)

#     try:
#         # 打开网页
#         driver.get(url)

#         # 等待页面加载完成（显式等待）
#         wait = WebDriverWait(driver, 10)
#         # 等待某个元素加载完成（示例：等待阅读数元素出现）
#         read_count_element = wait.until(EC.presence_of_element_located((By.CLASS_NAME, "views")))

#         # 获取阅读数文本
#         read_count_text = read_count_element.text.strip()
#         # 移除固定前缀 "阅读数：" 并再次清理空白
#         read_count = read_count_text.replace("阅读数：", "").strip()

#         return read_count
#     except Exception as e:
#         return f"发生错误: {e}"
#     finally:
#         # 关闭浏览器
#         driver.quit()


def process_excel_file(
    file_path: str,
    sheet_name: str = None,  # 默认当前活动页签
    column_name: str = "J",  # 默认列名 "D"
    column_name1: str = "K",  # 默认列名 "E"
) -> None:
    """
    从Excel文件的指定页签和列中读取URL，统计阅读数并保存结果。

    Args:
        file_path (str): 输入Excel文件路径。
        sheet_name (str, optional): 页签名称。默认为当前活动页签。
        column_name (str, optional): 列名（如 "A", "B", "E"）。默认为 "D"。
        column_name1 (str, optional): 结果保存列名。默认为 "E"。
    """
    try:
        # 加载Excel文件
        wb = load_workbook(file_path)
        try:
            ws = wb[sheet_name] if sheet_name else wb.active
        except KeyError:
            print(f"工作表 '{sheet_name}' 不存在，将使用活动工作表。")
            ws = wb.active

        # 将列名（如 "E"）转换为列索引（如 5）
        column_index = openpyxl.utils.column_index_from_string(column_name)
        column_index1 = openpyxl.utils.column_index_from_string(column_name1)

        # 获取指定列的所有行值（跳过空值和非URL）
        rows_to_process = []
        for row_index, row in enumerate(
            ws.iter_rows(min_col=column_index, max_col=column_index, values_only=True),
            start=1,
        ):
            cell_value = row[0]
            if isinstance(cell_value, str) and cell_value.strip().startswith("http"):
                rows_to_process.append((row_index, cell_value))

        for row_index, cell_value in rows_to_process:
            # views = get_csdn_article_views(cell_value)
            # views_num = views.split(":")[1].strip()
            # ws.cell(row=row_index, column=column_index1, value=views_num)

            views = get_article_views(cell_value, use_random_ip=True)
            ws.cell(row=row_index, column=column_index1, value=views)

            # print(type(views_num))
            # print(views_num)
            # print(int(views_num))
            print(f"已更新行 {row_index} 的数据 URL: {cell_value}, Views: {views}")
            time.sleep(2)  # 避免请求过于频繁

        wb.save(file_path)
        print(f"结果已保存到: {file_path}")
    except FileNotFoundError:
        print(f"未找到文件: {file_path}")
    except Exception as e:
        print(f"处理 Excel 文件时发生未知错误: {e}")


def get_article_views(url, use_random_ip=False):
    """
    从InfoQ文章URL获取阅读量（data.views）

    Args:
        url (str): InfoQ文章URL
        use_random_ip (bool): 是否使用随机IP

    Returns:
        int: 文章的阅读量，如果获取失败返回None
    """

    """
    使用上下文管理器临时禁用SSL警告
    """
    # 临时禁用所有警告
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=UserWarning, module="urllib3")

        # 从URL中提取UUID
        try:
            uuid = url.split("/")[-1]
            if not uuid:
                raise ValueError("Failed to obtain the UUID from the URL.")

            # 构造请求参数
            payload = {"uuid": uuid}

            # 构造请求URL
            api_url = "https://xie.infoq.cn/public/v1/article/getDetail"

            # 只保留最必要的请求头
            headers = {
                "Content-Type": "application/json",
                "Host": "xie.infoq.cn",
                "Origin": "https://xie.infoq.cn",
                "Referer": url,
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
            }

            # 如果需要随机IP，添加X-Forwarded-For头
            if use_random_ip:
                random_ip = f"{random.randint(1, 255)}.{random.randint(0, 255)}.{random.randint(0, 255)}.{random.randint(1, 254)}"
                headers["X-Forwarded-For"] = random_ip
                headers["X-Real-IP"] = random_ip
                print(f"使用随机IP: {random_ip}")

                session = requests.Session()
                adapter = HTTPAdapter(max_retries=3)
                session.mount("https://", adapter)

                # 发送POST请求
                response = requests.post(
                    api_url,
                    headers=headers,
                    json=payload,  # 使用json参数自动序列化并设置Content-Type
                    timeout=10,
                    verify=False,
                )

                # 检查响应状态
                response.raise_for_status()

                # 解析JSON响应
                data = response.json()

                # 提取views值
                views = data.get("data", {}).get("views")

                if views is not None:
                    print(f"文章阅读量: {views}")
                    return views
                else:
                    print("未找到data.views字段")
                    return "None"
        except Exception as e:
            print(f"错误: {e}")
            return "None"


# 示例使用
process_excel_file(
    file_path="C:/Users/qwx1425249/Desktop/data/开发者空间案例内外媒运营数据看板.xlsx",
    sheet_name="案例发布计划",  # 指定页签名称（可选
    column_name="J",  # 指定列名（可选）
    column_name1="K",
)
